package library.console;

import java.sql.SQLException;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;

import library.*;

public class BookingMenu {
	Scanner scanner;
	Reader currentReader;
	ReaderController readerController;
	BookController bookController;
	BookingController booking;
	
	public BookingMenu(Scanner sc){
		scanner = sc;
		
		try {
			readerController = new ReaderController();
			bookController = new BookController();
			System.out.print("Enter reader Name: ");
	//		int reader_id = Integer.parseInt(scanner.nextLine());
			String readerName = scanner.nextLine();
			currentReader = (Reader) readerController.getReader(readerName);
			booking = new BookingController(currentReader);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Error: " + e.getMessage() + ", Return to main menu.");
			return;
		}
		showUserInfo();
		showMenu();
	}

	private void showMenu() {
		int option;

		do {
			option = -1;
			System.out.println("============================");
			System.out.println("  Select option ");
			System.out.println("============================");
			System.out.println("  1: Show booking record ");
			System.out.println("  2: Insert booking record ");
			System.out.println("  3: Search book");
			System.out.println("  4: To Main Menu");
			System.out.println("============================");
			
			try{
				option = scanner.nextInt();
			} catch (InputMismatchException misMatchEx){
				System.out.println("Invalid option, your input is not a number.");
				option = -1;
			} finally {
				scanner.nextLine();
			}

			switch(option){
				case 1:
					showBookedRecord();
					break;
				case 2:
					createBookingRecord();
					break;
				case 3:
					searchBook();
					break;
				case 4:
					return;
				default:
					System.out.println("Invalid option, please enter a number between 1 to 4.");
					break;
			}
			System.out.println("Press Enter to continue....");
		} while (option != 4);
	}	
	
	private void showUserInfo() {
		System.out.println("==================================");
		System.out.println("|       User Information          |");
		System.out.println("==================================");
		System.out.println("  User Name: " + currentReader.getName() + " User id: "+ currentReader.getId());
		System.out.println("  User Tel: " + currentReader.getTel());
		System.out.println("============================");
	}
	
	private void showBookedRecord(){
		System.out.println("+---------------------------------------------------------------------+");
        System.out.println("|       Booking record                                                |");
        System.out.println("+---------------------------------------------------------------------+");
		List<BookingRecord> recordList = null;
		try {
			recordList = booking.getBookingRecord();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(recordList.size() > 0){
            System.out.printf(" %s \t %-40s \t %s \n","#" ,"Book name", "Return Date");
			for(int i=0;i<recordList.size();i++){
                BookingRecord cur_bk = recordList.get(i);
                System.out.printf(" %s \t %-40s \t %s \n",i+1 ,cur_bk.getBookName(), cur_bk.getBorrowDate());
			//	System.out.println(recordList.get(i).toString());
            }
		}
		else
			System.out.println("  No record.  ");
        System.out.println("---------End of booking record-----------------------------------------");
	}

	private void createBookingRecord(){
        int book_id;
        do{
            book_id = -2;
            System.out.print("Enter book id, enter -1 to exit: ");
            book_id = scanner.nextInt();
            scanner.nextLine();
            try {
                Book newReservedBook = booking.bookRecord(book_id);
                System.out.printf("Book: %s booked.\n", newReservedBook.getName());
            } catch(NullPointerException exNull){
                System.out.printf("Book id: %s cannot be found. (%s)", book_id , exNull.getMessage());
                continue;
            } catch (Exception e) {
                System.out.println("Can not reserve required item, " + e.getMessage());
                continue;
            }
        } while (book_id != -1);

	}

    private void searchBook(){
        System.out.print("Enter searching keyword: ");
        String keyword = scanner.nextLine();
        List<Book> result = null;
        try {
            BookController bookController = new BookController();
            result = bookController.search(keyword);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("---------------------------------------------------");
        System.out.println("  Search result");
        System.out.println("---------------------------------------------------");
        System.out.println("There are " + result.size() + " item(s) found.");
        System.out.printf(" %s \t %-40s \t %s \n","#" ,"Book name", "Status");
        for(int i=0;i<result.size();i++){
            Book cur_bk = result.get(i);
            System.out.printf(" %s \t %-40s \t %s \n",i+1 ,cur_bk.getName(), cur_bk.getStatus());
        }
    }

	public static void returnBook(Scanner sc){
		System.out.println("Return book, enter -1 to exit: ");
        int input_id = -1;
        do{
            try {
                System.out.print("Enter book ID that want to return:");
                input_id = sc.nextInt();
                if(input_id == -1)
                    return;
                BookingController booking = new BookingController(null);
                Book bk = booking.returnBooked(input_id);
                System.out.println("Book " + bk.getName() + " returned.");
            }catch (InputMismatchException in){
                System.out.println("Your input is not a number, please enter a valid book id");
                continue;
            }
            catch (Exception e) {
                // TODO Auto-generated catch block
                System.out.println("Error when return books: " + e.getMessage());
                continue;
            } finally {
                sc.nextLine();
            }


        } while (input_id != -1);
	}
}
